/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.acao;

import Data.ClienteDAO;
import Data.FilmeDAO;
import Data.RetiradaDAO;
import Model.ClienteBean;
import Model.FilmeBean;
import Model.RetiradaBean;
import Model.UsuarioBean;
import Util.Utilidades;
import View.CadastroCliente;
import View.CadastroFilme;
import View.TelaPrincipal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael
 */
public class FazerRetirada extends javax.swing.JInternalFrame {

    private float total = 0;

    /**
     * Creates new form FazerRetirada
     */
    public FazerRetirada() {
        initComponents();
        criarTabela();
        jftf_total.setValue(0);
        data_retirada.setValue(new Date());
        data_devolucao.setValue(Utilidades.getInstance().data_devolucao(new Date()));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtf_cliente = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jtf_nome_filme = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jftf_total = new javax.swing.JFormattedTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jtf_id_cliente = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        data_retirada = new javax.swing.JFormattedTextField();
        data_devolucao = new javax.swing.JFormattedTextField();
        jCheckBox1 = new javax.swing.JCheckBox();

        setTitle("Fazer retirada");

        jLabel1.setText("Cliente:");

        jtf_cliente.setEditable(false);

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Filme:");

        jtf_nome_filme.setEditable(false);

        jButton2.setText("Buscar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Data da Retirada: ");

        jLabel4.setText("Data de Devolução: ");

        jLabel5.setText("Valor Total: ");

        jftf_total.setEditable(false);
        jftf_total.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getCurrencyInstance())));

        jButton3.setText("Salvar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Cancelar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jtf_id_cliente.setEditable(false);

        jButton5.setText("Add");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("Remover");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        data_retirada.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        data_retirada.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                data_retiradaFocusLost(evt);
            }
        });
        data_retirada.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                data_retiradaKeyReleased(evt);
            }
        });

        data_devolucao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

        jCheckBox1.setText("Pagar");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(jLabel1)
                                            .addGap(18, 18, 18)
                                            .addComponent(jtf_id_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(jtf_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(jLabel4)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(data_devolucao, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(jLabel3)
                                            .addGap(18, 18, 18)
                                            .addComponent(data_retirada, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGap(18, 18, 18)
                                    .addComponent(jButton1))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jtf_nome_filme, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton6))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(jftf_total, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jCheckBox1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)
                        .addGap(47, 47, 47))))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton3, jButton4});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton2, jButton5, jButton6});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtf_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jtf_id_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(data_retirada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(data_devolucao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtf_nome_filme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(jButton5)
                    .addComponent(jButton6))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jftf_total, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jCheckBox1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        CadastroCliente cc = new CadastroCliente();
        cc.setCamposCampos(jtf_cliente, jtf_id_cliente);
        TelaPrincipal.adicionarInternalFrame(cc);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        CadastroFilme cf = new CadastroFilme();
        cf.setCampos(jtf_nome_filme);
        TelaPrincipal.adicionarInternalFrame(cf);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        //Validação de filme selecionado
        if (!jtf_nome_filme.getText().isEmpty() && !jtf_nome_filme.getToolTipText().isEmpty() && jtf_nome_filme.getToolTipText().matches("\\d+")) {

            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();

            for (int i = 0; i < modelo.getRowCount(); i++) {
                if (modelo.getValueAt(i, 0).toString().equals(jtf_nome_filme.getToolTipText())) {
                    JOptionPane.showMessageDialog(rootPane, "O Filme ja está na lista Selecione outro!");
                    return;
                }
            }

            FilmeDAO data = new FilmeDAO();

            Vector linha = new Vector();


            try {
                FilmeBean filme = data.getFilme(Integer.parseInt(jtf_nome_filme.getToolTipText()));
                linha.addElement(filme.getCodigo());
                linha.addElement(filme.getTitulo_portugues());
                linha.addElement(filme.getMidia().getDescricao());
                linha.addElement(filme.getMidia().getValor());
                linha.addElement(filme.getValor_adiciona());

                modelo.addRow(linha);

                total += filme.getValorTotal();

                jftf_total.setValue(total);

                jtf_nome_filme.setText("");
                jtf_nome_filme.setToolTipText("");

            } catch (Exception ex) {
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "Selecione um filme atraves do campo Buscar");
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        if (jTable1.getSelectedRow() != -1) {
            FilmeDAO data = new FilmeDAO();
            try {
                FilmeBean filme = data.getFilme(Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()));

                total -= filme.getValorTotal();
                jftf_total.setValue(total);

                DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
                modelo.removeRow(jTable1.getSelectedRow());
            } catch (SQLException ex) {
                Logger.getLogger(FazerRetirada.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Selecione um registro primeiro!");
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if (validarCampos()) {

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

            RetiradaDAO retirada_data = new RetiradaDAO();
            FilmeDAO filme_data = new FilmeDAO();
            ClienteDAO cliente_data = new ClienteDAO();

            ClienteBean cliente = null;
            UsuarioBean usuario = new UsuarioBean();

            usuario.setCodigo(1);
            try {
                cliente = cliente_data.getCliente(Integer.parseInt(jtf_id_cliente.getText()));
            } catch (SQLException ex) {
                return;
            }

            List<RetiradaBean> retiradas = new ArrayList<>();

            //Percorro todas as linhas da tabela em busca dos filmes
            for (int i = 0; i < jTable1.getRowCount(); i++) {
                try {

                    FilmeBean filme = filme_data.getFilme(Integer.parseInt(jTable1.getValueAt(i, 0).toString()));

                    if (!filme_data.isDisponivel(filme.getCodigo())) {
                        JOptionPane.showMessageDialog(rootPane, "O filme: " + filme.getTitulo_portugues() + " não está disponivel, verifique!");
                        return;
                    }
                    RetiradaBean retirada = new RetiradaBean();

                    retirada.setCliente(cliente);
                    retirada.setFilme(filme);
                    try {
                        retirada.setData_retirada(sdf.parse(data_retirada.getText()));
                    } catch (ParseException ex) {
                        throw new SQLException(ex);
                    }
                    try {
                        retirada.setData_devolucao(sdf.parse(data_devolucao.getText()));
                        //TODO colocar o usuario que vem da tela principal ja logado
                    } catch (ParseException ex) {
                        throw new SQLException(ex);
                    }

                    retirada.setUsuario(usuario);
                    retirada.setValor(filme.getValorTotal());

                    retiradas.add(retirada);
                } catch (SQLException ex) {
                    Logger.getLogger(FazerRetirada.class.getName()).log(Level.SEVERE, null, ex);
                }

            } // Fim do loop que percorre os filmes
            try {

                boolean resultado;

                if (jCheckBox1.isSelected()) {
                    //Retirada com pagamento
                    resultado = retirada_data.gravarRetirada(retiradas, true);
                } else {
                    //Retirada sem pagamento
                    resultado = retirada_data.gravarRetirada(retiradas, false);
                }

                if (resultado) {
                    JOptionPane.showMessageDialog(rootPane, "Sucesso!");
                    limparCampos();
                } else {
                    throw new SQLException("Problema ao inserir registro");
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(rootPane, "Erro: \n" + ex.getMessage());
            }

        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void data_retiradaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_data_retiradaKeyReleased
    }//GEN-LAST:event_data_retiradaKeyReleased

    private void data_retiradaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_data_retiradaFocusLost

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            data_devolucao.setValue(Utilidades.getInstance().data_devolucao(sdf.parse(data_retirada.getText())));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "erro ao calcular data de devolução!");
        }

    }//GEN-LAST:event_data_retiradaFocusLost
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField data_devolucao;
    private javax.swing.JFormattedTextField data_retirada;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JFormattedTextField jftf_total;
    private javax.swing.JTextField jtf_cliente;
    private javax.swing.JTextField jtf_id_cliente;
    private javax.swing.JTextField jtf_nome_filme;
    // End of variables declaration//GEN-END:variables

    private void criarTabela() {
        Vector cabeçalho = new Vector();

        cabeçalho.addElement("Codigo");
        cabeçalho.addElement("Nome do Filme em Portugues");
        cabeçalho.addElement("Midia");
        cabeçalho.addElement("Valor da Midia");
        cabeçalho.addElement("Valor adicional");

        DefaultTableModel modelo = new DefaultTableModel(cabeçalho, 0);

        jTable1.setModel(modelo);
    }

    private boolean validarCampos() {

        if (jtf_id_cliente.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Selecione um cliente!");
            return false;
        }

        if (data_devolucao.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Escolha uma data para devolução!");
            return false;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        Date retirada;
        Date devolucao;

        try {
            retirada = sdf.parse(data_retirada.getText());
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(rootPane, "Data de retirada invalida!");
            return false;
        }

        try {
            devolucao = sdf.parse(data_devolucao.getText());
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(rootPane, "Data de devolucao invalida!");
            return false;
        }

        if (devolucao.before(retirada)) {
            JOptionPane.showMessageDialog(rootPane, "Vai devolver antes de retirar mesmo ¬¬'");
            return false;
        }

        if (jTable1.getRowCount() < 1) {
            JOptionPane.showMessageDialog(rootPane, "Adiciona pelomenos 1 filme para ser alugado!");
            return false;
        }

        return true;
    }

    private void limparCampos() {
        jtf_cliente.setText("");
        jtf_id_cliente.setText("");
        jtf_nome_filme.setText("");
        jtf_nome_filme.setToolTipText("");
        data_devolucao.setValue(null);
        data_retirada.setValue(new Date());
        total = 0;
        jftf_total.setValue(total);
        jCheckBox1.setSelected(false);
        criarTabela();
    }
}